package net.esj.basic.plugins.spring.factory.xml.parser;

import net.esj.basic.dao.jdbc.JdbcSourceLocale;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

@Deprecated
public class JdbcSourceBeanDefinitionParser extends
		AbstractSingleBeanDefinitionParser {

	public static final String DEFAULT_JDBC_SOURCE_BEAN_NAME = JdbcSourceLocale.class.getName();
	
	public static final Class DEFAULT_JDBC_SOURCE_CLASS = JdbcSourceLocale.class;
	
	@Override
	protected void doParse(Element element, ParserContext parserContext,
			BeanDefinitionBuilder builder) {
		if (!parserContext.getRegistry().containsBeanDefinition(getBeanClassName(element))) {
			String dataSource = element.getAttribute("dataSource");
			if (!StringUtils.hasText(dataSource)) {
				dataSource = "dataSource";
			}
			builder.addPropertyReference("source", dataSource);
			parserContext.registerBeanComponent(
					new BeanComponentDefinition(builder.getBeanDefinition(),DEFAULT_JDBC_SOURCE_BEAN_NAME));
		}
	}

	@Override
	protected String getBeanClassName(Element element) {
		String className = element.getAttribute("class");
		if(!StringUtils.hasText(className)){
			className = DEFAULT_JDBC_SOURCE_BEAN_NAME;
		}
		return className;
	}

	@Override
	protected String resolveId(Element element,
			AbstractBeanDefinition definition, ParserContext parserContext)
			throws BeanDefinitionStoreException {
		String id = super.resolveId(element, definition, parserContext);
		if(StringUtils.hasText(id)){
			return id;
		}
		return DEFAULT_JDBC_SOURCE_BEAN_NAME;
	}
	
}
